#include <unistd.h>
#include "aliot.h"
#include "z_logger.h"
#include "aiot_state_api.h"

int aliot_error_check(const char *function, int32_t code) {
    if (code < STATE_SUCCESS) {
        log_error("%s = -0x%04X", function, -code);
    }
    return code;
}

int32_t aliot_state_log_cb(int32_t code, char *message) {
    char dup_message[1024];
    for (int i = 0; sizeof(dup_message); ++i) {
        if (message[i] == '\r' || message[i] == '\n' || message[i] == '\0') {
            dup_message[i] = '\0';
            break;
        } else {
            dup_message[i] = message[i];
        }
    }

    if (STATE_MQTT_LOG_HEXDUMP == code) {
        log_trace("%s", dup_message);
    } else {
        log_debug("%s", dup_message);
    }

    return STATE_SUCCESS;
}

void aliot_set_cred(aiot_sysdep_network_cred_t *cred) {
    extern const char *ali_ca_cert;

    bzero(cred, sizeof(aiot_sysdep_network_cred_t));
    //使用RSA证书校验MQTT服务端
    cred->option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA;
    //最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K
    cred->max_tls_fragment = 16384;
    //TLS建连时, 支持Server Name Indicator
    cred->sni_enabled = 1;
    //用来验证MQTT服务端的RSA根证书
    cred->x509_server_cert = ali_ca_cert;
    //用来验证MQTT服务端的RSA根证书长度
    cred->x509_server_cert_len = strlen(ali_ca_cert);
}

void *aliot_process_thread(void *args) {
    int32_t res = STATE_SUCCESS;

    if (!args) {
        aliot_error_check("aliot_process_thread", STATE_USER_INPUT_NULL_POINTER);
        return NULL;
    }

    log_debug("process_thread_enter");

    while (running) {
        log_trace("process_thread_loop");
        res = aiot_mqtt_process(args);
        aliot_error_check("aiot_mqtt_process", res);
        if (res < STATE_SUCCESS) {
            if (res == STATE_USER_INPUT_EXEC_DISABLED) {
                break;
            }
        }

        sleep(1);
    }

    log_debug("process_thread_exit");

    return NULL;
}